import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * java5 java.util.concurrent 的java并发库的使用(线程池、atomic...)
 */
public class ThreadConcurrent {

	public static void main(String[] args) {
		//线程池中有三个线程
//		ExecutorService executorService = Executors.newFixedThreadPool(3);
		//单线程(死掉后会自动重新创建一个)
//		ExecutorService executorService = Executors.newSingleThreadExecutor();
		//根据需要创建缓冲线程池
		ExecutorService executorService = Executors.newCachedThreadPool();
		//10个任务(task)扔(submit)到线程池(ThreadPool)中
		for(int i=0;i<10;i++){
			final int task = i;
			executorService.execute(new Runnable(){
				public void run() {
					for(int j=0;j<10;j++){
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println("execute "+ j +" of task " + task);
					}
				}
			});
		}
		executorService.shutdown();
//		executorService.shutdownNow();
		
		//schedule 调度线程池 类似 Timer,TimerTask
		ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
		scheduledExecutorService.schedule(new Runnable(){
			public void run() {
				System.out.println("bombing...");
			}
		}, 2, TimeUnit.SECONDS);
		
		scheduledExecutorService.scheduleAtFixedRate(new Runnable(){
			public void run() {
				System.out.println("bombing...");
			}
		}, 2, 5, TimeUnit.SECONDS);
	}
	
}
